package com.xbongbong.parent.abstracts;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.SubFormListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.BusinessSubFormListService;
import com.xbongbong.parent.parse.data.FormDataLinkDataLinkProductServiceImpl;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.parent.parse.data.LinkProductUpdateGetServiceImpl;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.model.DataDictionaryModel;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/11/19 11:14
 */
public abstract class AbstractBusinessSubFormListService<D> implements BusinessSubFormListService<D> {

    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private LinkProductUpdateGetServiceImpl linkProductUpdateGetService;
    @Resource
    private FormDataLinkDataLinkProductServiceImpl formDataLinkDataLinkProductService;
    @Resource
    private FormDataAnalysisHelp formDataAnalysisHelp;

    @Override
    public PaasFormDataEsListVO subFormList(SubFormListDTO subFormListDTO) throws XbbException {
        D formData = getFormData(subFormListDTO);

        Map<String, FieldAttrEntity> explainMap = getExplainList(subFormListDTO);
        return dealData(subFormListDTO, formData, explainMap);
    }


    @Override
    public Map<String, FieldAttrEntity> getExplainList(SubFormListDTO subFormListDTO) throws XbbException {
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(subFormListDTO.getCorpid(), subFormListDTO.getFormId(), subFormListDTO.getBusinessType());
        return ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
    }

    @Override
    public List<FieldAttrEntity> getSubExplainList(SubFormListDTO subFormListDTO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        String attr = subFormListDTO.getAttr();
        FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
        if (Objects.isNull(fieldAttrEntity)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.NOT_EXIST_FIELD);
        }
        List<FieldAttrEntity> subFormAttrList = new ArrayList<>();
        if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(),fieldAttrEntity.getFieldType()) || Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(),fieldAttrEntity.getFieldType())){
            for (FieldAttrEntity subAttrEntity : fieldAttrEntity.getSubForm().getItems()){
                // 字段回收站处理
                if (Objects.equals(subAttrEntity.getIsOpen(), 2)) {
                    subAttrEntity.setVisible(0);
                }
                subFormAttrList.add(subAttrEntity);
            }
        }else if (Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(), fieldAttrEntity.getFieldType())) {
            return getLinkProductExplainList(subFormListDTO, fieldAttrEntity);
        }
        subFormAttrList.removeIf(fieldAttrEntity1 -> Objects.equals(fieldAttrEntity1.getVisible(), 0));
        return subFormAttrList;
    }

    /**
     * 获取关联产品下的子字段
     * @param subFormListDTO
     * @param entity
     * @return
     * @throws XbbException
     */
    public List<FieldAttrEntity> getLinkProductExplainList(SubFormListDTO subFormListDTO, FieldAttrEntity entity) throws XbbException {
        String corpid = subFormListDTO.getCorpid();
        List<FieldAttrEntity> subFormAttrList = new ArrayList<>();
        Boolean isJxcUse = paasAppModel.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);

        proFormHelp.setProductAccuracy(entity,corpid,subFormListDTO.getUserId());
        for (FieldAttrEntity subAttrEntity : entity.getSubForm().getItems()){
            if (!ShowTypeEnum.listShow(subAttrEntity.getShowType())){
                continue;
            }

            // 字段回收站处理
            if (Objects.equals(subAttrEntity.getIsOpen(), 2)) {
                subAttrEntity.setVisible(0);
            }
            if (Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.UNIT.getAttr())){
                Long productFormId = paasFormModel.getFormIdByBusinessType(corpid, XbbRefTypeEnum.PRODUCT.getCode());
                List<ItemPoJo> itemPojoList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.PRODUCT_UNIT,corpid,productFormId);
                subAttrEntity.setItems(itemPojoList);
            }
            if (removeBySubAttr(subFormListDTO, subAttrEntity, isJxcUse)) {

                continue;
            }
            subFormAttrList.add(subAttrEntity);
        }
        subFormAttrList.removeIf(fieldAttrEntity1 -> Objects.equals(fieldAttrEntity1.getVisible(), 0));
        return subFormAttrList;
    }

    /**
     * 判断子表单内子字段是否需要显示在界面上
     * @param subFormListDTO
     * @param subAttrEntity
     * @return true:不可以显示在界面上；false：可以显示在界面
     */
    public boolean removeBySubAttr(SubFormListDTO subFormListDTO, FieldAttrEntity subAttrEntity, boolean isJxcUse) {
        return false;
    }
    /**
     * 判断子表单字段是否需要显示在界面上
     * @param subFormListDTO
     * @param subFormField
     * @return true:无权限；false：有权限
     */
    protected boolean noHasPermission(SubFormListDTO subFormListDTO, FieldAttrEntity subFormField, String creatorId) throws XbbException {
        if (Objects.isNull(subFormField)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.NOT_EXIST_FIELD);
        }
        //协同团队
        Long dataId = subFormListDTO.getDataId();
        List<String> ownerIdList;
        List<String> coUserList;
        List<Long> dataIdList = new ArrayList<>();
        dataIdList.add(dataId);
        Integer businessType = subFormListDTO.getBusinessType();
        String corpid = subFormListDTO.getCorpid();
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(dataIdList,corpid,businessType, false, mainUserMap,coUserMap);
        ownerIdList = mainUserMap.get(dataId);
        coUserList = coUserMap.get(dataId);

        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(creatorId, ownerIdList, coUserList, subFormListDTO.getUserId(), subFormListDTO.getLoginUser());
        return ExplainUtil.invisibleOfScope(subFormField, handlerExplainDTO);
    }

    protected PaasFormDataEsListVO getSubFormDataList(SubFormListDTO subFormListDTO, JSONObject data, D formDataEntity, List<FieldAttrEntity> subExplainList) throws XbbException{
        //模拟分页校验
        Integer page = subFormListDTO.getPage();
        Integer pageSize = subFormListDTO.getPageSize();
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 5 : pageSize;
        page = page < 1 ? 1 : page;
        Integer start = (page - 1) * pageSize;
        List<JSONObject> attrDataList = JSONArray.parseArray(data.getString(subFormListDTO.getAttr()),JSONObject.class);
        attrDataList = Objects.isNull(attrDataList) ? new ArrayList<>() : attrDataList;
        Integer dataSize = attrDataList.size();
        Integer end = start + pageSize;
        end = end > dataSize ? dataSize : end;
        List<PaasFormDataEntityExt> list = new ArrayList<>();
        if (dataSize < start + 1){

        }else {
            List<JSONObject> subAttrDataList = attrDataList.subList(start,end);
            for (JSONObject json : subAttrDataList){
                PaasFormDataEntityExt entityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(formDataEntity,entityExt);
                entityExt.setData(json);
                list.add(entityExt);
            }
        }
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        formDataListVO.setHeadList(subExplainList);
        formDataListVO.setPaasFormDataESList(list);
        Integer total = attrDataList.size();
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(subFormListDTO,formDataListDTO);
        formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
        //子表单金额千分位解析
        formDataListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, formDataListDTO.getAnalysisAmountOfThousandBitsWithOriginalValue());
        PageHelper pageHelper = new PageHelper(page,pageSize);
        pageHelper.setRowsCount(total);
        formDataListVO.setPageHelper(pageHelper);

        return formDataListVO;
    }

    public void transferProductFieldType(List<FieldAttrEntity> list) {
        list.forEach(item->{
            if (Objects.equals(item.getAttr(), SelectProductEnum.PRODUCT.getAttr())){
                item.setFieldType(FieldTypeEnum.TEXT.getType());
            }
        });
    }

    public void analysisDataList(SubFormListDTO subFormListDTO,   PaasFormDataEsListVO formDataListVO) throws XbbException {

        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(subFormListDTO,formDataListDTO);
        formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
        //子表单金额千分位解析
        formDataListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, formDataListDTO.getAnalysisAmountOfThousandBitsWithOriginalValue());

    }
}
